﻿using AutoMapper;
using Common.Domain;
using Common.Infrastructure.Repository;
using Common.Services;
using MediatR;
using System.Data;
using System.Xml.Linq;

namespace Business.WriteAPI.Application.Products
{
    public class ProductAddRequestHandler : IRequestHandler<ProductAddRequestModel, APIResult>
    {
        private IBaseRepository<Product> productRepository;
        private readonly IMapper mapper;
        public ProductAddRequestHandler(IBaseRepository<Product> productRepository, IMapper mapper)
        {
            this.productRepository = productRepository;
            this.mapper = mapper;
        }
        public Task<APIResult> Handle(ProductAddRequestModel request, CancellationToken cancellationToken)
        {
            APIResult result = new APIResult();
            result.Code = EnumCode.AddSuccess;
            result.Msg = "新增成功";

            Product product = mapper.Map<Product>(request);
            string nodeNo = "";
            var nodelist = productRepository.GetAll().OrderByDescending(x => x.ProductCode).FirstOrDefault();
            if (nodelist != null && !string.IsNullOrEmpty(nodelist.ProductCode))
            {
                string productCode = nodelist.ProductCode.Replace("P", "");
                if (int.TryParse(productCode, out int no))
                {
                    no += 1;
                    nodeNo = "P" + no.ToString().PadLeft(4, '0');
                }
                else
                {
                    // 处理无法解析为整数的情况
                    nodeNo = "P0001"; // 或者其他默认值
                }
            }
            else
            {
                // 处理 nodelist 为 null 或 ProductCode 为空的情况
                nodeNo = "P0001"; // 或者其他默认值
            }

            product.ProductCode = nodeNo;
            productRepository.Add(product);


            return Task.FromResult(result);
        }
    }
    public class ProductAddRequestModel : IRequest<APIResult>
    {
        public string ProductCode { get; set; }
        public int FoodId { get; set; }
        public string ProductionBatch { get; set; }
        public int ShelfLife { get; set; }
        public string LicenseNumber { get; set; }
        public string Enterprise { get; set; }
        public string Creator { get; set; }
        public DateTime CreateTime { get; set; } = DateTime.Now;
        public string Updator { get; set; }
        public DateTime UpdateTime { get; set; } = DateTime.Now;
        public string Deletor { get; set; }
        public DateTime DeleteTime { get; set; } = DateTime.Now;
        public string PhotoUrl { get; set; }
    }
}

